#!/usr/bin/env node

import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// 全面修复所有Java版本问题
function fixAllJavaVersions() {
    console.log('🔧 Starting comprehensive Java version fix...');
    
    const filesToCheck = [
        'android/app/capacitor.build.gradle',
        'android/capacitor-cordova-android-plugins/build.gradle',
        'android/app/build.gradle'
    ];
    
    let totalFixed = 0;
    
    filesToCheck.forEach(filePath => {
        const fullPath = path.join(__dirname, filePath);
        
        if (fs.existsSync(fullPath)) {
            let content = fs.readFileSync(fullPath, 'utf8');
            const originalContent = content;
            
            // 替换所有Java 21为Java 17
            content = content.replace(/JavaVersion\.VERSION_21/g, 'JavaVersion.VERSION_17');
            content = content.replace(/sourceCompatibility\s+JavaVersion\.VERSION_21/g, 'sourceCompatibility JavaVersion.VERSION_17');
            content = content.replace(/targetCompatibility\s+JavaVersion\.VERSION_21/g, 'targetCompatibility JavaVersion.VERSION_17');
            
            if (content !== originalContent) {
                fs.writeFileSync(fullPath, content);
                console.log(`✅ Fixed Java version in ${filePath}`);
                totalFixed++;
            } else {
                console.log(`✅ ${filePath} is already correct`);
            }
        } else {
            console.log(`❌ ${filePath} not found`);
        }
    });
    
    // 检查gradle.properties文件（不添加空的Java home配置）
    const gradlePropsPath = path.join(__dirname, 'android', 'gradle.properties');
    if (fs.existsSync(gradlePropsPath)) {
        let content = fs.readFileSync(gradlePropsPath, 'utf8');
        const originalContent = content;
        
        // 清理空的org.gradle.java.home配置
        content = content.replace(/^org\.gradle\.java\.home=\s*$/gm, '');
        content = content.replace(/\n\s*\n\s*\n/g, '\n\n'); // 清理多余的空行
        
        if (content !== originalContent) {
            fs.writeFileSync(gradlePropsPath, content);
            console.log('✅ Cleaned gradle.properties');
            totalFixed++;
        }
    }
    
    console.log(`🎉 Java version fix completed. ${totalFixed} file(s) updated.`);
    
    // 验证修复结果
    console.log('\n🔍 Verifying Java versions...');
    let hasJava21 = false;
    
    filesToCheck.forEach(filePath => {
        const fullPath = path.join(__dirname, filePath);
        if (fs.existsSync(fullPath)) {
            const content = fs.readFileSync(fullPath, 'utf8');
            if (content.includes('VERSION_21')) {
                console.log(`❌ ${filePath} still contains VERSION_21`);
                hasJava21 = true;
            }
        }
    });
    
    if (!hasJava21) {
        console.log('✅ All Java versions are now set to 17');
    } else {
        console.log('❌ Some files still contain Java 21');
    }
}

// 运行修复
fixAllJavaVersions();
